<template>
    <div class="search-suggestion-container">
        <van-cell icon="search"
            v-for="(suggestion, index) in suggestionList"
            :key="index"
            @click="$emit('search', suggestion)"
        >
            <div slot="title" v-html="highLight(suggestion)"></div>
        </van-cell>
    </div>
</template>

<script>
import { debounce } from 'lodash';
import * as Api from 'api/common';

export default {
    name: 'search_suggestion',
    components: {
    },
    props: {
        searchText: {
            type: String,
            require: true
        }
    },
    // 监控data中的数据变化
    watch: {
        searchText: {
            handler: debounce(function () {
                this.getSearchSuggestion();
            }, 200),
            immediate: true
        }
    },
    // 定义属性
    data () {
        return {
            suggestionList: []
        };
    },
    // 计算属性，会监听依赖属性值随之变化
    computed: {
    },
    // 方法集合
    methods: {
        async getSearchSuggestion () {
            const params = {
                q: this.searchText
            };
            const res = await Api.reqDev('/v1_0/suggestion', 'get', { params });
            // console.log(res);
            if (res.message === 'OK') {
                this.suggestionList = res.data.options;
            }
        },
        highLight (str) {
            return str.replace(new RegExp(`(${this.searchText})`, 'gi'), '<span style="color: red">$1</span>');
        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created () {
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
    }
};
</script>

<style lang='less' scoped>
</style>
